package com.game.plus2048;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.game.plus2048.NewGameActivity.DescendingScoreComparator;
import com.game.plus2048.NewGameActivity.HScore;
import com.theosirian.twokfortyeight.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView tvcount;
	private Game game;
	private TextView tv;
	private RelativeLayout board;
	private int[][] gameState;
	private static int currentId = 0;
	private int highScoreMin = 0, realHighScore = 0;
	private int width, height, win_score, glow1, glow2;
	private boolean beatenHighScore = false;
	private String scoreKey = "com.theosirian.twokfortyeight.SCOREBOARD_KEY",
			p_name = "";
	private String[] hScoresPrefix = {
			"com.theosirian.twokfortyeight.SCOREBOARD_1",
			"com.theosirian.twokfortyeight.SCOREBOARD_2",
			"com.theosirian.twokfortyeight.SCOREBOARD_3",
			"com.theosirian.twokfortyeight.SCOREBOARD_4",
			"com.theosirian.twokfortyeight.SCOREBOARD_5",
			"com.theosirian.twokfortyeight.SCOREBOARD_6",
			"com.theosirian.twokfortyeight.SCOREBOARD_7",
			"com.theosirian.twokfortyeight.SCOREBOARD_8",
			"com.theosirian.twokfortyeight.SCOREBOARD_9",
			"com.theosirian.twokfortyeight.SCOREBOARD_10" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		resetId();
		final RelativeLayout tl = (RelativeLayout) findViewById(R.id.touch_listener);

		final GestureDetector myGesture = new GestureDetector(this,
				new MyGestureListener());

		tl.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return myGesture.onTouchEvent(event);
			}
		});

		tl.setClickable(true);

		if (savedInstanceState != null) {

			height = savedInstanceState.getInt("height", 4);
			width = savedInstanceState.getInt("width", 4);

			// final int rate = (height >= width) ? 86 - ((height - 4) * 17)
			// : 86 - ((width - 4) * 17);
			int rate = 0;
			if (height == 4) {
				rate = 86;
			}
			if (height == 5) {
				rate = 69;
			}
			if (height == 6) {
				rate = 55;
			}

			final int hw = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, rate, getResources()
							.getDisplayMetrics());

			gameState = new int[height][width];

			for (int i = 0; i < height; i++) {

				for (int j = 0; j < width; j++) {

					gameState[i][j] = savedInstanceState.getInt(
							"gs" + String.valueOf(i) + String.valueOf(j), 0);

				}

			}

			win_score = savedInstanceState.getInt("win_score", 2048);

			game = new Game(savedInstanceState.getInt("score", 0),
					savedInstanceState.getInt("time", 0), gameState,
					savedInstanceState.getInt("rUndo", 1), win_score, height,
					width);

			board = (RelativeLayout) findViewById(R.id.board);

			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

			board.setLayoutParams(layoutParams);

			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int i = 0; i < height; i++) {

				for (int j = 0; j < width; j++) {

					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
							hw, hw);

					tv = (TextView) inflater.inflate(R.layout.text_view, null);

					tv.setId(nextId());

					if (tv.getId() == 1) {

						params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
						params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
						board.addView(tv, params);

					} else if ((tv.getId() - 1) % width == 0) {

						params.addRule(RelativeLayout.BELOW, tv.getId() - width);
						board.addView(tv, params);

					} else {

						params.addRule(RelativeLayout.BELOW, tv.getId() - width);
						params.addRule(RelativeLayout.RIGHT_OF, tv.getId() - 1);
						board.addView(tv, params);

					}

				}

			}

			Animation zoomio = AnimationUtils
					.loadAnimation(this, R.anim.zoomio);

			updateTextViewWOA();
			updateTextCount();
			tv = (TextView) findViewById(glow1 + 1);
			tv.startAnimation(zoomio);

			tv = (TextView) findViewById(glow2 + 1);
			tv.startAnimation(zoomio);

		} else {

			Intent intent = getIntent();

			p_name = intent.getStringExtra("player_name");

			win_score = intent.getIntExtra("win_score", 2048);

			height = intent.getIntExtra("grid_height", 4);
			width = intent.getIntExtra("grid_width", 4);

			game = new Game(height, width, win_score);

			board = (RelativeLayout) findViewById(R.id.board);

			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

			board.setLayoutParams(layoutParams);

			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			// final int rate = (height >= width) ? 86 - ((height - 4) * 17)
			// : 86 - ((width - 4) * 17);
			int rate = 0;
			if (height == 4) {
				rate = 86;
			}
			if (height == 5) {
				rate = 69;
			}
			if (height == 6) {
				rate = 56;
			}
			final int hw = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, rate, getResources()
							.getDisplayMetrics());

			for (int i = 0; i < height; i++) {

				for (int j = 0; j < width; j++) {

					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
							hw, hw);

					tv = (TextView) inflater.inflate(R.layout.text_view, null);

					tv.setId(nextId());

					if (tv.getId() == 1) {

						params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
						params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
						board.addView(tv, params);

					} else if ((tv.getId() - 1) % width == 0) {

						params.addRule(RelativeLayout.BELOW, tv.getId() - width);
						board.addView(tv, params);

					} else {

						params.addRule(RelativeLayout.BELOW, tv.getId() - width);
						params.addRule(RelativeLayout.RIGHT_OF, tv.getId() - 1);
						board.addView(tv, params);

					}

				}

			}

			SharedPreferences sharedPref = this.getSharedPreferences(scoreKey,
					Context.MODE_PRIVATE);

			List<Integer> hScores = new ArrayList<Integer>();

			String key;

			for (int i = 0; i < hScoresPrefix.length; i++) {

				key = hScoresPrefix[i] + String.valueOf(height)
						+ String.valueOf(width);
				hScores.add(sharedPref.getInt(key, 0));

			}

			Collections.sort(hScores);

			realHighScore = hScores.get(hScores.size() - 1);
			highScoreMin = hScores.get(0);

			tv = (TextView) findViewById(R.id.tvhscore);
			tv.setText(String.valueOf(realHighScore));

			game.nextClearSpace();
			updateTextView();
			updateTextCount();
			game.nextClearSpace();
			updateTextView();
			updateTextCount();
		}

	}

	private int nextId() {

		currentId += 1;
		return currentId;

	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);

		gameState = game.getGameState();

		savedInstanceState.putInt("height", game.getHeight());
		savedInstanceState.putInt("width", game.getWidth());

		for (int i = 0; i < height; i++) {

			for (int j = 0; j < width; j++) {

				savedInstanceState.putInt(
						"gs" + String.valueOf(i) + String.valueOf(j),
						gameState[i][j]);

			}

		}

		savedInstanceState.putInt("score", game.getScore());
		savedInstanceState.putInt("time", game.getTime());
		savedInstanceState.putInt("rUndo", game.getUndos());
		savedInstanceState.putInt("win_score", game.getWinScore());

	}

	public Bitmap takeScreenshot() {
		View rootView = findViewById(android.R.id.content).getRootView();
		rootView.setDrawingCacheEnabled(true);
		return rootView.getDrawingCache();
	}

	public void saveBitmap(Bitmap bitmap) {
		File imagePath = new File(Environment.getExternalStorageDirectory()
				+ "/screenshot.png");
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(imagePath);
			bitmap.compress(CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			Log.e("GREC", e.getMessage(), e);
		} catch (IOException e) {
			Log.e("GREC", e.getMessage(), e);
		}
	}

	class MyGestureListener extends SimpleOnGestureListener {

		private static final int SWIPE_MIN_DISTANCE = 50;

		private static final int SWIPE_MAX_OFF_PATH = 500;

		private static final int SWIPE_THRESHOLD_VELOCITY = 50;

		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {

			float dX = e2.getX() - e1.getX();

			float dY = e1.getY() - e2.getY();

			if (Math.abs(dY) < SWIPE_MAX_OFF_PATH
					&& Math.abs(velocityX) >= SWIPE_THRESHOLD_VELOCITY
					&& Math.abs(dX) >= SWIPE_MIN_DISTANCE && !game.isLost()) {

				if (dX > 0) {

					if (game.onRightSwipe()) {

						updateTextView();
						updateTextCount();
					}

					if (game.isWon()) {

						showWinDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					} else if (game.isLost()) {

						showDefeatDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					}

				} else {

					if (game.onLeftSwipe()) {

						updateTextView();
						updateTextCount();
					}
					if (game.isWon()) {

						showWinDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					} else if (game.isLost()) {

						showDefeatDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					}

				}

				return true;

			} else if (Math.abs(dX) < SWIPE_MAX_OFF_PATH
					&& Math.abs(velocityY) >= SWIPE_THRESHOLD_VELOCITY
					&& Math.abs(dY) >= SWIPE_MIN_DISTANCE && !game.isLost()) {

				if (dY > 0) {

					if (game.onUpSwipe()) {

						updateTextView();
						updateTextCount();
					}
					if (game.isWon()) {

						showWinDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					} else if (game.isLost()) {

						showDefeatDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					}

				} else {

					if (game.onDownSwipe()) {

						updateTextView();
						updateTextCount();
					}
					if (game.isWon()) {

						showWinDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					} else if (game.isLost()) {

						showDefeatDialog();

						if (beatenHighScore) {

							newHighScore(game.getScore());

						}

					}

				}

				return true;

			}

			return false;

		}

	}

	class HScore {
		String name;
		Integer score;

		public HScore(String n, Integer s) {
			this.name = n;
			this.score = s;
		}

		public String getName() {
			return name;
		}

		public Integer getScore() {
			return score;
		}
	}

	class ScoreComparator implements Comparator<HScore> {
		@Override
		public int compare(HScore o1, HScore o2) {
			return o1.getScore().compareTo(o2.getScore());
		}
	}

	class DescendingScoreComparator implements Comparator<HScore> {
		@Override
		public int compare(HScore o1, HScore o2) {
			return o2.getScore().compareTo(o1.getScore());
		}
	}

	private void newHighScore(int newHS) {

		SharedPreferences sharedPref = this.getSharedPreferences(scoreKey,
				Context.MODE_PRIVATE);

		List<HScore> savedHScores = new ArrayList<HScore>();

		String keyS, keyN;

		for (int i = 0; i < hScoresPrefix.length; i++) {

			keyS = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width);
			keyN = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width) + "N";

			savedHScores.add(new HScore(sharedPref.getString(keyN, "------"),
					sharedPref.getInt(keyS, 0)));

		}

		savedHScores.add(new HScore(p_name, game.getScore()));

		Collections.sort(savedHScores, new DescendingScoreComparator());

		SharedPreferences.Editor editor = sharedPref.edit();

		for (int i = 0; i < hScoresPrefix.length; i++) {

			keyS = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width);
			keyN = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width) + "N";

			editor.putInt(keyS, savedHScores.get(i).getScore());
			editor.putString(keyN, savedHScores.get(i).getName());

		}

		editor.commit();

	}

	private void updateTextCount() {
		tvcount = (TextView) findViewById(R.id.touchcount);
		tvcount.setText(String.valueOf(game.getCountTouch()));
	}

	private void updateTextView() {

		gameState = game.getGameState();

		tv = (TextView) findViewById(R.id.tvscore);
		tv.setText(String.valueOf(game.getScore()));

		if (game.getScore() >= highScoreMin) {

			if (game.getScore() >= realHighScore) {

				tv = (TextView) findViewById(R.id.tvhscore);
				tv.setText(String.valueOf(game.getScore()));

			}

			beatenHighScore = true;

		}

		tv = (TextView) findViewById(game.getGlowId() + 1);

		Animation zoomio = AnimationUtils.loadAnimation(this, R.anim.zoomio);
		tv.startAnimation(zoomio);

		for (int i = 0; i < height; i++) {

			for (int j = 0; j < width; j++) {

				tv = (TextView) findViewById((i * width) + j + 1);

				tv.setText(String.valueOf(gameState[i][j]));

				switch (gameState[i][j]) {
				default:
					tv.setBackgroundResource(R.drawable.bg_tv);
					tv.setTextColor(Color.parseColor("#00F5F5F5"));
					break;
				case 2:
					tv.setBackgroundResource(R.drawable.bg_2);
					tv.setTextColor(Color.parseColor("#776e65"));
					break;
				case 4:
					tv.setBackgroundResource(R.drawable.bg_4);
					tv.setTextColor(Color.parseColor("#776e65"));
					break;
				case 8:
					tv.setBackgroundResource(R.drawable.bg_8);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 16:
					tv.setBackgroundResource(R.drawable.bg_16);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 32:
					tv.setBackgroundResource(R.drawable.bg_32);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 64:
					tv.setBackgroundResource(R.drawable.bg_64);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 128:
					tv.setBackgroundResource(R.drawable.bg_128);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 256:
					tv.setBackgroundResource(R.drawable.bg_256);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 512:
					tv.setBackgroundResource(R.drawable.bg_512);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 1024:
					tv.setBackgroundResource(R.drawable.bg_1024);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 2048:
					tv.setBackgroundResource(R.drawable.bg_2048);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;

				}

			}

		}

	}

	private void updateTextViewWOA() {

		gameState = game.getGameState();

		tv = (TextView) findViewById(R.id.tvscore);
		tv.setText(String.valueOf(game.getScore()));

		if (game.getScore() >= highScoreMin) {

			if (game.getScore() >= realHighScore) {

				tv = (TextView) findViewById(R.id.tvhscore);
				tv.setText(String.valueOf(game.getScore()));

			}

			beatenHighScore = true;

		}

		for (int i = 0; i < height; i++) {

			for (int j = 0; j < width; j++) {

				tv = (TextView) findViewById((i * width) + j + 1);

				tv.setText(String.valueOf(gameState[i][j]));

				switch (gameState[i][j]) {
				default:
					tv.setBackgroundResource(R.drawable.bg_2048);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 0:
					tv.setBackgroundResource(R.drawable.bg_tv);
					tv.setTextColor(Color.parseColor("#00F5F5F5"));
					break;
				case 2:
					tv.setBackgroundResource(R.drawable.bg_2);
					tv.setTextColor(Color.parseColor("#776e65"));
					break;
				case 4:
					tv.setBackgroundResource(R.drawable.bg_4);
					tv.setTextColor(Color.parseColor("#776e65"));
					break;
				case 8:
					tv.setBackgroundResource(R.drawable.bg_8);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 16:
					tv.setBackgroundResource(R.drawable.bg_16);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 32:
					tv.setBackgroundResource(R.drawable.bg_32);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 64:
					tv.setBackgroundResource(R.drawable.bg_64);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 128:
					tv.setBackgroundResource(R.drawable.bg_128);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 256:
					tv.setBackgroundResource(R.drawable.bg_256);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 512:
					tv.setBackgroundResource(R.drawable.bg_512);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 1024:
					tv.setBackgroundResource(R.drawable.bg_1024);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;
				case 2048:
					tv.setBackgroundResource(R.drawable.bg_2048);
					tv.setTextColor(Color.parseColor("#F5F5F5"));
					break;

				}

			}

		}

	}

	private void resetId() {

		currentId = 0;

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("SdCardPath")
	public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
		switch (paramMenuItem.getItemId()) {
		default:
			return super.onOptionsItemSelected(paramMenuItem);

		case android.R.id.home:
			Log.d("TEST", "DASDSAD");
		case R.id.action_restart:
			showRestartDialog();
			return true;
			// case R.id.action_settings:
			// //startActivity(new Intent(this, SettingsActivity.class));
			// return true;

		case R.id.action_quit:
			showQuitDialog();
			return true;
		case R.id.action_scoreboard:
			showScoreboard();
			return true;
		case R.id.action_share:
			Bitmap bitmap = null;
			bitmap = takeScreenshot();
			saveBitmap(bitmap);
			Bitmap icon = bitmap;
			Intent share = new Intent(Intent.ACTION_SEND);
			share.setType("image/jpeg");
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
			File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
			try {
			    f.createNewFile();
			    FileOutputStream fo = new FileOutputStream(f);
			    fo.write(bytes.toByteArray());
			} catch (IOException e) {                       
			        e.printStackTrace();
			}
			share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
			startActivity(Intent.createChooser(share, "Share Image")); 

			/*
			 * if (!game.undoLastMove()) {
			 * 
			 * paramMenuItem.setEnabled(false);
			 * 
			 * }
			 * 
			 * paramMenuItem.setTitle(paramMenuItem.getTitle() + " (" +
			 * game.getUndos() + ")");
			 */

			return true;
		}
	}

	private void showScoreboard() {

		SharedPreferences sharedPref = this.getSharedPreferences(scoreKey,
				Context.MODE_PRIVATE);

		List<HScore> savedHScores = new ArrayList<HScore>();

		String keyS, keyN;

		for (int i = 0; i < hScoresPrefix.length; i++) {

			keyS = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width);
			keyN = hScoresPrefix[i] + String.valueOf(height)
					+ String.valueOf(width) + "N";

			savedHScores.add(new HScore(sharedPref.getString(keyN, "------"),
					sharedPref.getInt(keyS, 0)));

		}

		Collections.sort(savedHScores, new DescendingScoreComparator());

		final Dialog dialog2 = new Dialog(MainActivity.this);
		dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog2.setContentView(R.layout.dialog_scoreboard);
		TextView tvTitle = (TextView) dialog2.findViewById(R.id.tvtitle);
		tvTitle.setText("High Scores (" + String.valueOf(height) + "x"
				+ String.valueOf(height) + ")");
		Button close = (Button) dialog2.findViewById(R.id.b_sb_quit);
		close.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				dialog2.dismiss();

			}

		});

		LinearLayout sbll = (LinearLayout) dialog2.findViewById(R.id.sb_ll);

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		LinearLayout sbRow;
		TextView tv;

		for (int i = 0; i < 10; i++) {

			sbRow = (LinearLayout) inflater.inflate(R.layout.scoreboard_row,
					null);

			tv = (TextView) sbRow.findViewById(R.id.sb_name);
			tv.setText(savedHScores.get(i).getName());

			tv = (TextView) sbRow.findViewById(R.id.sb_score);
			tv.setText(String.valueOf(savedHScores.get(i).getScore()));

			sbll.addView(sbRow);

		}

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog2.getWindow().getAttributes());
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;

		dialog2.show();

		dialog2.getWindow().setAttributes(lp);

	}

	public void showMenu(View v) {

		MainActivity.this.openOptionsMenu();

	}

	public void showQuitDialog() {
		new AlertDialog.Builder(this)
				.setTitle("Quit")
				.setMessage("Do you really want to quit?")
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface di, int which) {
								finish();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int which) {
						di.dismiss();
					}
				}).show();
	}

	public void showWinDialog() {
		new AlertDialog.Builder(this)
				.setTitle("Congratulations!")
				.setMessage(
						"You've finished the game and won a lhama, your score is "
								+ game.getScore() + " in " + game.getTimeF()
								+ ".\nDo you wish to play again?")
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface di, int which) {
								game = new Game(height, width, win_score);
								game.nextClearSpace();
								glow1 = game.getGlowId();
								game.nextClearSpace();
								glow2 = game.getGlowId();
								recreate();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int which) {
						di.dismiss();
					}
				}).show();
	}

	public void showDefeatDialog() {
		new AlertDialog.Builder(this)
				.setTitle("Game Over")
				.setMessage(
						"No more valid moves, your final score is "
								+ game.getScore() + " in " + game.getTimeF()
								+ ".\nDo you wish to play again?")
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface di, int which) {
								game = new Game(height, width, win_score);
								game.nextClearSpace();
								glow1 = game.getGlowId();
								game.nextClearSpace();
								glow2 = game.getGlowId();
								recreate();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int which) {
						di.dismiss();
					}
				}).show();
	}

	public void showRestartDialog() {
		new AlertDialog.Builder(this)
				.setTitle("Restart Game?")
				.setMessage("Do you really want to restart the game?")
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface di, int which) {
								game = new Game(height, width, win_score);
								game.nextClearSpace();
								glow1 = game.getGlowId();
								game.nextClearSpace();
								glow2 = game.getGlowId();
								recreate();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface di, int which) {
						di.dismiss();
					}
				}).show();
	}

}
